<template>
    <el-tabs v-model="activeName">

        <el-tab-pane label="流程配置" name="flow">
            <br />
            工单分类：
            <el-select v-model="selectedCategory_flow" placeholder="请选择工单分类" @change="getFlowStr">
                <el-option v-for="category in categoryData" :key="category.id" :label="category.name"
                    :value="category.id"></el-option>
            </el-select>
            <br /><br />
            <el-row>
                <el-col :span="2">工单流程：</el-col>
                <el-col :span="8">
                    <el-steps :active=10>
                        <el-step v-for="item in currentFlow" :title="item.title" :key="item.id" />
                    </el-steps>
                </el-col>
            </el-row>
            <br />
            工单流程选择：
            <el-transfer :titles="['待选', '已选']" v-model="flow" :data="statusData" :props="{ key: 'id', label: 'name' }"
                target-order="push" /><br />
            <el-button type="primary" style="margin-left: 10px;" @click="confirmFlow">确认配置</el-button><br />
        </el-tab-pane>

        <el-tab-pane label="职责配置" name="duty">
            <br />
            工单分类：
            <el-select v-model="selectedCategory_duty" placeholder="请选择工单分类" @change="getDutyEmployee">
                <el-option v-for="category in categoryData" :key="category.id" :label="category.name"
                    :value="category.id"></el-option>
            </el-select>
            <br /><br />

            职责人员：
            <el-cascader class="custom-cascader" v-model="selectedEmps" :options="roleOptions" :props="props"
                :show-all-levels="false" @change="" placeholder="按角色选择" collapse-tags clearable />
            <br /><br />

            选中人员：
            <el-row>
                <!-- 一个方框，用来显示已选择的人员 -->
                <div class="selected-employee">
                    <el-tag class="mytag" size="large" v-for="item in dutyEmps" :key="item.value" :label="item.label">
                        {{ item.label }}
                    </el-tag>
                    <!-- closable @close="closeTag(item.value)" -->
                </div>
            </el-row>
            <br /><br />

            <el-button type="primary" style="margin-left: 10px;" @click="confirmDuty">确认配置</el-button><br />
            <!-- <el-button type="primary" style="margin-left: 10px;"
                @click="console.log(selectedEmps)">打印选择项</el-button><br /> -->
        </el-tab-pane>

    </el-tabs>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';
const router = useRouter();

import { employeeGetFormedService } from '@/api/user.js';
import { workorderSetFlowService, workorderSetDutyService, workorderGetCategoryService, workorderGetStatusService, workorderGetCategoryDutyService } from '@/api/workorder.js';

const activeName = ref('flow')  // 激活视图页

// 流程配置相关
let flowStr = '';
const currentFlow = ref() // 当前的流程
let staticStatusData;
const statusData = ref([{ key: 0, label: '' }])   // 供选择的状态
const flow = ref([]) // 选择好的流程
const categoryData = ref([{ id: 0, name: '', flow: '' }]) // 供选择的工单分类
const selectedCategory_flow = ref()    // 当前选中要配置流程的工单分类id
const selectedCategory_duty = ref()    // 当前选中要配置职责人员的工单分类id
const confirmFlow = async () => {
    if (selectedCategory_flow.value != '' && flow.value.length > 0) {
        try {
            let result = await workorderSetFlowService(selectedCategory_flow.value, flow.value)
            if (result.code == 200) {
                ElMessage.success(result.msg)
                selectedCategory_flow.value = null
                currentFlow.value = []
                getcategoryData()
            } else if (result.code == 401) {
                ElMessage.error(result.msg)
                router.push({ path: '/login' });
            } else {
                ElMessage.error(result.msg)
            }
        } catch {
            ElMessage.error('系统异常 (setFlow)')
            console.log(error)
        }
        // axios({
        //     method: "post",
        //     url: 'http://localhost:8081/workorder/category/flow',
        //     headers: { 'Authorization': localStorage.getItem("jwtToken") },
        //     data: {
        //         categoryId: selectedCategory_flow.value,
        //         flow: flow.value
        //     }
        // }).then(function (response) {
        //     if (response.data.code == 200) {
        //         ElMessage.success(response.data.msg)
        //         selectedCategory_flow.value = null
        //         currentFlow.value = []
        //         // currentFlow.value = flow.value
        //         getcategoryData()
        //     }
        //     else if (response.data.code == 401) {
        //         ElMessage.error(response.data.msg)
        //         router.push({ path: '/login', query: {} });
        //         return;

        //     }
        //     else {
        //         ElMessage.error(response.data.msg)
        //     }
        // }).catch(function (error) {
        //     ElMessage.error('系统异常')
        // });
    }
    else {
        ElMessage.error('请选择工单分类和流程')
    }
}
async function getcategoryData() {
    try {
        let result = await workorderGetCategoryService();
        if (result.code == 200) {
            categoryData.value = result.data;
        } else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.error(result.data.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (getcategory)')
        console.log(error)
    }
}
async function getStatusData() {
    try {
        let result = await workorderGetStatusService();
        if (result.code == 200) {
            staticStatusData = result.data;
            statusData.value = result.data;

        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
        else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (getStatus)')
        console.log(error)
    }
}
// 获取当前选中工单分类的flowArr
function getFlowStr() {
    for (let i = 0; i < categoryData.value.length; i++) {
        if (categoryData.value[i].id == selectedCategory_flow.value) {
            flowStr = categoryData.value[i].flow
            if (flowStr != null) {
                let flowStrArr = flowStr.split(',')
                let flowArr = flowStrArr.map(Number)
                flowArr.pop()
                transferFlowStr(flowArr)
            } else {
                currentFlow.value = []
                ElMessage.warning('当前工单分类没有配置流程')
            }

            break
        }
    }
}
// 将flowArr转换成el-steps可识别的格式
function transferFlowStr(flowArr) {
    currentFlow.value = []
    for (let i = 0; i < flowArr.length; i++) {

        for (let j = 0; j < staticStatusData.length; j++) {

            if (flowArr[i] == staticStatusData[j].id) {
                currentFlow.value.push({ title: staticStatusData[j].name, id: staticStatusData[j].id })
                break
            }
        }
    }
}

//*****************************************************************//

// 职责配置相关
const props = {   // cascader的配置值
    expandTrigger: 'hover',// as const,    // 鼠标上悬时展开
    multiple: true, // 多选
    emitPath: false // 只返回被选中的值，不返回路径值
}

const roleOptions = ref();  // cascader的选项,格式化的员工数据
const dutyEmps = ref(); // 查得的当前配置的职责人员（用于前端循环渲染tags）
const selectedEmps = ref(); // 当前选中的职责人员（用于传递给后端去更新职责人员）

// 从选中人员的标签中关闭某个标签
const closeTag = (closeItem) => {
    selectedValue.value = selectedValue.value.filter(item => item.value !== closeItem)
}
async function getFormedEmployee() {
    try {
        let result = await employeeGetFormedService();
        if (result.code == 200) {
            roleOptions.value = result.data;
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
        else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (getFormedEmployee)')
        console.log(error)
    }
}
async function getDutyEmployee() {
    try {
        let result = await workorderGetCategoryDutyService(selectedCategory_duty.value);
        if (result.code == 200) {
            dutyEmps.value = result.data;
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
        else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (getDutyEmployee)')
        console.log(error)
    }
}
async function confirmDuty() {
    try {
        let result = await workorderSetDutyService(selectedCategory_duty.value, selectedEmps.value);
        if (result.code == 200) {
            ElMessage.success(result.msg)
            getDutyEmployee()
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        }
        else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (setDuty)')
        console.log(error)
    }
}

getcategoryData()
getStatusData()
getFormedEmployee()

</script>

<style>
.selected-employee {
    border: 1px solid #409eff;
    border-radius: 4px;
    height: 200px;
    width: 50%;
    margin-top: 10px;
    padding: 10px;
}


.custom-cascader {
    margin-top: 10px;
}

.mytag {
    margin: 5px;
}
</style>